import { useEffect, useState } from "react";
import { useAliveController } from 'react-activation'
import { Skeleton } from "antd";
import { FCMainFrame, NavigateMode } from "@components";
import { session } from "@core";

import codesJson from "./codes.json";
import { queryCfgCodeList, getUserMenuAuthCode, findUserAuthUnits, findUnitProductType, findUnits } from "@apis/indexApi";

import { getGrantedMenu } from "@routes/fullMenuConfig";

import { MainContext } from "@contexts/MainContext";

const collapsed = false;
const siderWidth = 200;
const collapsedSiderWidth = 80;
const headerHeight = 64;
const tabBarHeight = 60;

// 后端返回的权限code
const defaultPermissions = [
  '010000','020100','030100','040100','050100','050200','050300','060100','060200','060300','070100','070200','070300','070302','070400','080100','080200','080300','630100','630200','630300'
]

const Main = () => {
  const { clear } = useAliveController()

  const [menuItems, setMenuItems] = useState([]);
  const [loading, setLoading] = useState(false);
  async function getPermissions() {
    const permissions = await getUserMenuAuthCode();
    setLoading(true);
    
    if (!permissions.length) return
    session.set('permissions', permissions)
    setMenuItems(getGrantedMenu({ permissions }));

    // session.set('permissions', defaultPermissions)
    // setMenuItems(getGrantedMenu({ permissions: defaultPermissions }));

  }

  const [codes, setCodes] = useState([...codesJson]) // 数据字典
  async function loadCommonCodesFun() {
    const newCodes = await queryCfgCodeList();
    setCodes([...newCodes]);
  }

  /**
   * 返回数据字典指定项
   * @param {*} codeKey
   * @returns
   */
  const getCode = (codeKey) => {
    if (!codeKey && !codes.length ) return null
    const arr = codes?.filter((code) => code.codeKey === codeKey)
    if (arr) {
      return arr[0]
    }
    return null
  }

  // 是否需要按钮
  const isButtomShow = (e) => {
    const permissions = session.get('permissions')
    return permissions?.find((i) => i === e) ? true : false
  }

  useEffect(() => {
    getPermissions()
    loadCommonCodesFun();
    return () => {
      clear()
    }
  }, []);
  

  return (
    <>
      <MainContext.Provider value={{ codes, getCode, isButtomShow }}>
        {loading ? (
          <FCMainFrame
            navigateMode={NavigateMode.sideMenu}
            collapsed={collapsed}
            siderWidth={siderWidth}
            collapsedSiderWidth={collapsedSiderWidth}
            menuItems={menuItems}
            headerHeight={headerHeight}
            tabBarHeight={tabBarHeight}
          />
        ) : (
          <div style={{ paddingTop: "10px", width: "50%" }}>
            <Skeleton active />
          </div>
        )}
      </MainContext.Provider>
    </>
  );
};

export default Main;
